﻿
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using SolidWorks.Interop.sldworks;

namespace Yuri.SolidWorks.MainFunction
{
    public class ConnectSwApp
    {

        static SldWorks _swApp;

        /// <summary>
        /// SolidWorks主程序
        /// </summary>
        public static SldWorks swApp
        {
            get
            {
                GetSwApp();
                return _swApp;
            }
            set => _swApp = value;
        }


        /// <summary>
        /// 获取SolidWorks程序
        /// </summary>
        /// <returns></returns>
        public static bool GetSwApp()
        {
            //判断当前是否已经获取
            if (_swApp != null)
            {
                try
                {
                    _swApp.GetProcessID();
                    return true;
                }
                catch (Exception) { _swApp = null; }
            }

            //判断当前无打开的SolidWorks
            Process[] processArr = Process.GetProcessesByName("SLDWORKS");

            if (processArr.Length > 0)
            {
                try
                {
                    _swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                    if (_swApp != null) return true;
                }
                catch (Exception) { }
              
            }
            else
            {
                if (MessageBox.Show("是否打开SolidWorks？", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    List<swSetupPath> swSetupPaths = getSwSetupPaths();
                    if (swSetupPaths.Count != 0)
                    {
                        //安装了单一版本直接进行启动
                        if (swSetupPaths.Count == 1)
                        {
                            Process process = Process.Start(swSetupPaths.First().setupPath);

                            int sleepTime = 0;
                            while (sleepTime < 30 * 1000)
                            {
                                Thread.Sleep(1000);
                                sleepTime += 1000;

                                try
                                {
                                    _swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                                    if (_swApp != null) return true;
                                }
                                catch (Exception) { }
                            }

                        }
                        //安装了多个版本进行选择启动
                        else
                        {

                        }


                    }
                }

            }

            return false;

        }


        /// <summary>
        /// 由安装软件注册表进行查找安装列表
        /// </summary>
        /// <returns></returns>
        internal static List<swSetupPath> getSwSetupPaths()
        {
            List<swSetupPath> swSetupPaths = new List<swSetupPath>();

            string registry_key = @"SOFTWARE\SolidWorks";

            try
            {
                RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);

                RegistryKey key = hklm.OpenSubKey(registry_key);

                foreach (var item in key.GetSubKeyNames())
                {

                    if (!item.ToUpper().Contains("SOLIDWORKS")) continue;

                    for (int i = 1992; i <= DateTime.Now.Year; i++)
                    {

                        if (item.ToUpper() != "SOLIDWORKS " + i.ToString()) continue;

                        RegistryKey subkey = key.OpenSubKey(item + "\\Setup");

                        if (subkey != null)
                        {
                            string versionName = item;

                            var V = subkey.GetValue("SolidWorks Folder");
                            string setupPath = Convert.ToString(subkey.GetValue("SolidWorks Folder")) + "SLDWORKS.EXE";

                            //启动程序存在，添加至列表
                            if (File.Exists(setupPath))
                            {
                                swSetupPaths.Add(new swSetupPath(versionName, setupPath));
                            }

                        }

                    }

                }
            }
            catch (Exception ex)
            {

            }

            return swSetupPaths;
        }


        /// <summary>
        /// SolidWorks安装列表
        /// </summary>
        internal class swSetupPath
        {
            public swSetupPath(string versionName, string setupPath)
            {
                this.versionName = versionName;
                this.setupPath = setupPath;
            }

            public string versionName;
            public string setupPath;

        }


    }
}
